package org.thesis.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.thesis.doituong.showToast;
import org.thesis.secutity.AESControl;
import org.thesis.secutity.DEScontrol;
import org.thesis.secutity.KeyManager;
import org.thesis.secutity.RSAControl;
import org.thesis.secutity.TripleDEScontrol;
import org.thesis.secutity.webserviceRequest;

import org.thesis.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class encryptActivity extends Activity 
{
	final static String ENC_PUBLIC = "ENC4@";
	final static String ENC_AES = "AES@";
	final static String ENC_DES = "DES@";
	final static String ENC_TDES = "3DES@";
	final static String ENC_FOOT = "@encrypt";
	final static String PUBLIC_KEY = "Public key ";
	final static String PATH_GET_KEY_DE = "/EncryptEmail/getkey_de/";
	final static String PATH_PUBLIC = "/EncryptEmail/keymail/";
	final static String DESede = "3DES";
	final static String SIGN = "SignByEsafe@";
	final static String KEY_SIGN = "KEY_SIGN";
	final static String KEY_NGUOIGUI_NGUOINHAN = "KEY_NGUOIGUI_NGUOINHAN";
	final static  int RESULT_ENCRYPT = 1234;
	final static String KEY_CHUOI_ATTACH_SEND = "chuoi_attach_send";
	final static String KEY_CHUOI_MESS_ENCRYPT = "CHUOI_MESS_ENCRYPT";
	final static String KEY_MESSAGE = "MEASSAGE BODY";
	final static String KEY_NGUOIGUI = "NGUOIGUI";
	final static String KEY_NGUOINHAN = "NGUOINHAN";
	final static String KEY_ATTACH_ENCRYPT = "ATTACH_DA_MAHOA";
	showToast st;
	TextView txt_int_att, txt_encrypt, txt_sign;
	EditText et_plantext;
	Button btn_mahoa,btn_taokey;
	String str_mess_encrypt, tag = "encryptActuvity";
	int i_att;
	int requestCode =  1;
	//
	String str_nguoigui, str_nguoinhan,str_mess_plantext, str_att;
	
	String str_URL; // dia chi server
	String keyname; //loaikey ma hoa
	String loaimahoa; //loai ma hoa
	
	KeyManager mykey;
	AESControl aes;
	DEScontrol des;
	RSAControl rsa;
	TripleDEScontrol tdes;
	///
	final static String[] cacloaimahoa ={"AES","DES","3DES"};///
	TextView  txt_loaimahoa;///
	String str_nguoigui_nguoinhan, str_loaimahoa, str_namekeyfile, str_pathkey, str_mess_send;//
	org.thesis.secutity.webserviceRequest webservice;///
	
	org.thesis.secutity.AESControl AEScontrol;///
	org.thesis.secutity.KeyManager keymanager;///
	
	String str_sign;
	String progress, progress2; // thong bao khi async getkey hoac ma hoa;
	boolean flag_getkey = false, flag_enc_publickey = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.encrypt2);
		st = new showToast(this);
		//NHAN THONG TIN BEN NEWMAIL GUI QUA
		Intent i_get = getIntent();
		str_nguoigui = i_get.getStringExtra(KEY_NGUOIGUI);
		str_nguoinhan = i_get.getStringExtra(KEY_NGUOINHAN);
		str_mess_plantext = i_get.getStringExtra(KEY_MESSAGE);
		str_att = i_get.getStringExtra(KEY_CHUOI_ATTACH_SEND);
		str_mess_send = str_mess_plantext;
		str_mess_encrypt = str_mess_plantext;
		str_sign = "";
		//
		str_nguoigui_nguoinhan = getIntent().getStringExtra("KEY_NGUOIGUI_NGUOINHAN");///
		//
		Log.v(tag, "da nhan dc 4 thong tin ben new mail: " 
				+ str_nguoigui +"gui qua, chuoi att :  " + str_att + "--nguoi gui ng nhan : " +str_nguoigui_nguoinhan);
		//
		String[]arr_att = str_att.split(";");
		txt_int_att = (TextView) findViewById(R.id.txt_encrypt_int_att);
		txt_encrypt = (TextView) findViewById(R.id.txt_encrypt_encrypt);
		et_plantext = (EditText) findViewById(R.id.et_encrypt_plantext);
		txt_sign = (TextView)findViewById(R.id.txt_encrypt_sign);
		txt_loaimahoa = (TextView)findViewById(R.id.txt_encrypt_thuatmahoa);///
		et_plantext.setText(str_mess_plantext);
		if(str_att.length() > 1) // neu chuoi att ko bi trong
			txt_int_att.setText(String.valueOf(arr_att.length));
		
		///
		str_loaimahoa = txt_loaimahoa.getText().toString();///
		mykey = new KeyManager();
		keymanager = new org.thesis.secutity.KeyManager();///
		
	}
	
	public void img_onClick(View v)
	{
		ImageButton img = (ImageButton)v;
		switch (img.getId()) {
		case R.id.img_encrypt_backA:
			finish();break;
		case R.id.img_encrypt_menu:
			openOptionsMenu();break;
		case R.id.img_encrypt_file:
			Log.v(tag, "new intent attach encrypt");
			Intent intent = new Intent(this, org.thesis.activity.attach_encryptActivity.class);
			intent.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
			intent.putExtra(KEY_NGUOIGUI_NGUOINHAN, str_nguoigui_nguoinhan);
			intent.putExtra(KEY_NGUOINHAN, str_nguoinhan);
			startActivityForResult(intent, requestCode);
			break;

		default:
			break;
		}
	}
	public void btn_onClick(View v)
	{
		Button btn = (Button)v;
		switch (btn.getId()) {
		case R.id.btn_encrypt_ky:
			sign_action_send();
			break;
		case R.id.btn_encrypt_encrypt:
			dialog2();
			txt_encrypt.setText(str_mess_encrypt);
			break;
		case R.id.btn_encrypt_OK:
			//gui cac thong tin da ma hoa ve cho newmail gui dy
			Log.v(tag, "ok ..");
			Intent intent = new Intent();
			intent.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
			intent.putExtra(KEY_CHUOI_MESS_ENCRYPT, str_mess_encrypt);
			intent.putExtra(KEY_SIGN, str_sign);
			setResult(RESULT_ENCRYPT, intent);
			finish();
		default:
			break;
		}
	}
	
	//menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_encrypt, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.item_encrypt_createAllkey:
			create_all_key();
			create_key_rsa();
			break;
		case R.id.item_encrypt_encrypt:
			dialog2();
			txt_encrypt.setText(str_mess_encrypt);
			break;
		case R.id.item_encrypt_file:
			Intent intent = new Intent(this, org.thesis.activity.attach_encryptActivity.class);
			intent.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
			intent.putExtra(KEY_NGUOIGUI_NGUOINHAN, str_nguoigui_nguoinhan);
			intent.putExtra(KEY_NGUOINHAN, str_nguoinhan);
			startActivityForResult(intent, requestCode);
			break;
		case R.id.item_encrypt_sign:
			sign_action_send();
			break;

		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}
	
	
	
 
	
	// nhan chuoi attach sau khi ma hoa gui ve
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case RESULT_OK:
			str_att = data.getStringExtra(KEY_ATTACH_ENCRYPT);
			Log.v(tag, "nhan duoc chuoi att sau khi ma hoa " + str_att);
			break;

		default:
			break;
		}
	}
	
	///tttt
	@Override
    protected Dialog onCreateDialog(int id) {///
    	
    	switch(id){
    		case 0:{
    			return new AlertDialog.Builder(this)
    				.setIcon(R.drawable.lock)
    				.setTitle(getResources().getString(R.string.select_encrypt2))
    				.setPositiveButton("OK!", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							txt_loaimahoa.setText(str_loaimahoa);
							encrypt_action();
							//EncryptActivity.this.finish();
						}
					})
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					})
					.setSingleChoiceItems(cacloaimahoa, -1, new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							str_loaimahoa = cacloaimahoa[which].toString();
							
						}
					})

					
					.create();								
    		}
    	}
    	
		return null;
		
	}

 public void encrypt_create_key(){///
	 try{
		 str_loaimahoa = "AES";/////
		 Log.v(tag, "start create key ...");
			str_mess_plantext = et_plantext.getText().toString().trim();
			if(str_mess_plantext.equals("")){
				Toast.makeText(getBaseContext(), "Chua nhap noi dung plain text", Toast.LENGTH_SHORT).show();
				Log.i(tag, "chua nhap Noi dung plain text ");
			}else{
				//Kiem tra thuat toan ma hoa da duoc chon chua;
				Log.i("loaimahoa= ", str_loaimahoa);
				if(str_loaimahoa.equalsIgnoreCase("")){
					//chon loai ma hoa: AES, DES, 3DES;
					Toast.makeText(getBaseContext(), getResources().getString(R.string.err_createkey_1), Toast.LENGTH_SHORT).show();
				
				}else{
					
//					str_namekeyfile = str_nguoigui_nguoinhan+str_loaimahoa+".key";
//					if(str_loaimahoa.equalsIgnoreCase("3DES")){////
//						str_loaimahoa  = DESede;
//						}
						str_namekeyfile  = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
						Log.v("str_namekeyfile = ",  str_namekeyfile);////
					Log.v(tag, "bat dau tao key : " + str_namekeyfile);
					File savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/keymail");
					savedirsub.mkdirs();
					str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_namekeyfile;
					Log.v(tag,"tao thu muc");
					File f = new File(str_pathkey);
			        if(!f.isFile())
			        {
			        	//chua co key trong thu muc emailkey ==>goi ham gui request len server lay key ve roi luu tru;
			        	Log.i(tag, "chua co key trong thu muc emailkey ==> request key");
			        	Log.v(tag, "str_nguoigui_nguoinhan="+str_nguoigui_nguoinhan);
			        	Log.v(tag, "str_loaimahoa="+str_loaimahoa);
			        	webservice = new org.thesis.secutity.webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);			        
			        	webservice.getkeyStringEncrypt();
			        	Log.i(tag, "Da tao xong key va luu xuong sdcard/EncrypEmail/keymail");
						
			        }else {
			        	//co key trong thu muc emailkey ==> thong bao da co key roi
						Toast.makeText(getBaseContext(), "Da ton tai key", Toast.LENGTH_SHORT).show();
						Log.i(tag,"co key trong thu muc emailkey");
			        }
				
				}
				Log.v(tag, "create key");
			}
			
		}catch(Exception e){
			Log.v(tag, "ERROR: "+e);
		}
 }
 
 
 
 	
 	
 	
 	
 	public String encrypt_3des() //ham ky, tra ve chuoi plantext
 	{
 		String output = "";
 		str_mess_plantext = et_plantext.getText().toString().trim();
 		try 
 		{
// 			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_PUBLIC;
//            path += "/key3des.key";
 			String path = str_pathkey;
 			Log.v(tag, "path :  " + path);
			File f = new File(path);
			if(!f.isFile())
			{
				Log.v(tag, "file key khong ton tai");
				
			}
			else
			{
				Log.v(tag, "Da co key, ma hoa 3 des");
				tdes = new TripleDEScontrol(mykey.getKey3DES(path));
				output = tdes.encrypt(str_mess_plantext);
				Log.v(tag, "ma hoa thanh cong 3des ... " + output);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err encrypt 3des " +e.toString());
		}
 		str_mess_encrypt = output;
 		return output;
 	}
 	
 	public String encrypt_des() //ham ky, tra ve chuoi plantext
 	{
 		String output = "";
 		str_mess_plantext = et_plantext.getText().toString().trim();
 		try 
 		{
// 			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_PUBLIC;
//            path += "/keydes.key";
 			String path = str_pathkey;
 			Log.v(tag, "path :  " + path);
			File f = new File(path);
			if(!f.isFile())
			{
				Log.v(tag, "file key khong ton tai");
			}
			else
			{
				Log.v(tag, "Da co key, ma hoa  des");
				des = new DEScontrol(mykey.getKeyDES(path));
				output = des.Encrypt(str_mess_plantext);
				Log.v(tag, "ma hoa thanh cong des ... " + output);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err encrypt des " +e.toString());
		}
 		str_mess_encrypt = output;
 		return output;
 	}
 	

 	public String encrypt_aes() 
 	{
 		String output = "";
 		str_mess_plantext = et_plantext.getText().toString().trim();
 		try 
 		{
// 			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_PUBLIC;
//            path += "/keyaes.key";
 			String path = str_pathkey;
 			Log.v(tag, "path :  " + path);
			File f = new File(path);
			if(!f.isFile())
			{
				Log.v(tag, "file key khong ton tai");
				
			}
			else
			{
				Log.v(tag, "Da co key, ma hoa 3 des");
				aes = new AESControl(mykey.getKeyAES(path));
				output = aes.Encrypt(str_mess_plantext);
				Log.v(tag, "ma hoa thanh cong aes... " + output);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err encrypt aes " +e.toString());
		}
 		str_mess_encrypt = output;
 		return output;
 	}
 	
 	public String encrypt_rsa_publickey()
 	{
 		String output = "";
 		str_mess_plantext = et_plantext.getText().toString().trim();
 		try 
 		{
 			String path = str_pathkey;
 			Log.v(tag, "path :  " + path);
			File f = new File(path);
			if(!f.isFile())
			{
				Log.v(tag, "file key khong ton tai");
				
			}
			else
			{
				Log.v(tag, "Da co key, ma hoa voi public key");
				rsa = new RSAControl(path, false);
				output = rsa.encrypt_baomat(str_mess_plantext);
				Log.v(tag, "ma hoa thanh cong public key. " + output);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "err encryptpublic key " +e.toString());
		}
 		str_mess_encrypt = output;
 		return output;
 	}
 	
 	public void create_all_key()  // tao key de tesst
 	{
 		try 
 		{
 			File savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/keymail");
 			if(!savedirsub.isDirectory())
 				savedirsub.mkdirs();
 			
 			//tao key rsa 
 			create_key_rsa();
 			//
			String pathDES = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+"keydes.key";
			String path3DES = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+"key3des.key";
			String pathAES = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+"keyaes.key";
			File fdes = new File(pathDES);
			File f3des = new File(path3DES);
			File faes = new File(pathAES);
			if(!fdes.isFile())
			{
				Log.v(tag, "file des chua co, tao key");
				mykey.taoKey("DES", 128, pathDES);
				Log.v(tag, "tao des ok");
			}
			if(!f3des.isFile())
			{
				mykey.taoKey("DESede", 128, path3DES);
				Log.v(tag, "tao key 3des ok");
			}
			if(!faes.isFile())
			{
				mykey.taoKey("AES", 128, pathAES);
				Log.v(tag, "tao key aes ok");
			}

			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi create all key ... " +e.toString());
		}
 	}
 	
 	public void create_key_rsa()  // tao cap key rsa noi bo de tesst
	{
		try {
			mykey = new KeyManager();
    		String keyPu = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC + "/keypu.key";
			String keyPri = Environment.getExternalStorageDirectory().getAbsolutePath() +PATH_PUBLIC+ "/keypri.key";
			File f = new File(keyPu);
//			mykey.createRSAkey(keyPu, keyPri);
			if(!f.isFile())
			{
				mykey.createRSAkey(keyPu, keyPri);
			}else
				Log.v(tag, "key da ton tai...");
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "ERR create key rsa " + e.toString());
		}
	}
 	
 	
 	public void encrypt_action()
 	{
 		try
 		{
// 			str_loaimahoa = "AES";
 			if(str_mess_plantext.length() == 0)
 			{
 				st.showmess(getResources().getString(R.string.err_encrypt_plantext));
 			}
 			else
 			{
 				if(str_loaimahoa.equals(""))
 				{
 					st.showmess(getResources().getString(R.string.ChonLoaiMaHoa));
 				}
 				else
 				{
 					flag_enc_publickey = false;
 					str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
 			 		Log.v("str_namekeyfile = ",  str_namekeyfile);////
 			 		File savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC);
 			 		if(!savedirsub.isDirectory())
 			 		{
 							savedirsub.mkdirs();
 							Log.v(tag,"tao thu muc");
 			 		}
 			 		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_namekeyfile;
 			 		
 			 		//neu dung public key de ma hoa, doi duong dan
 			 		if(str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY))
 			 		{
 			 			flag_enc_publickey = true;
 			 			Log.v("str_nguoinhan=",str_nguoinhan);////
 			 			if(str_nguoinhan.split(";").length==1)
 			 			{
 			 				str_nguoinhan=str_nguoinhan.replaceAll(";", "").trim();
 			 				File savedirsubPUB = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_GET_KEY_DE);
 		 			 		if(!savedirsubPUB.isDirectory())
 		 			 		{
 		 			 			savedirsubPUB.mkdirs();
 		 							Log.v(tag,"tao thu muc");
 		 			 		}
 			 				String path_key_pu_encrypt = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_GET_KEY_DE+str_nguoinhan+" keypu.key";
 			 				str_pathkey = path_key_pu_encrypt;
 			 				Log.v(tag, "path_key_pu_encrypt = "+path_key_pu_encrypt);////
 			 			}
 			 		}
 			 			
 			 			
 			 		File f = new File(str_pathkey);
 				      if(!f.isFile())
 				      {
 				    	 flag_getkey = true;
 				      	 progress = getResources().getString(R.string.getkey);
 				      	 progress2 = getResources().getString(R.string.getkey_suc);
 				      	 new sync_encrypt().execute("createkey");
 				      }
 				      else
 				      {
 				    	  flag_getkey = false;
 				    	  progress = getResources().getString(R.string.enc_action);
 				    	  progress2 = getResources().getString(R.string.enc_suc);
 				    	  new sync_encrypt().execute("mahoa");
 				      }
 				}
 			}
 			
// 			hienthi();
 				
 			
 		}catch (Exception e) {
			// TODO: handle exception
 			Log.v(tag, "Err encrypt action " +e.toString());
		}
 		
 	}
 	
 	 public void create_key()
 	 {
 	 	try 
 	 	{
 	 		if(flag_enc_publickey) // xin key public
 	 		{
 	 			Log.v(tag, "file pulbic key de ma hoa chua ton tai , bat dau tao key");
				webservice  = new webserviceRequest(str_nguoigui_nguoinhan, "RSApu");
				webservice.getPuRSAKey_encrypt(str_nguoinhan);
				Log.v(tag, "xin key thanh cong");
 	 		}
 	 		else
 	 		{
 	 	//chua co key trong thu muc emailkey ==>goi ham gui request len server lay key ve roi luu tru;
		      	Log.i(tag, "chua co key trong thu muc emailkey ==> request key");
		      	Log.i("tag","truoc khi goi ham request web service voi nguoigui_nguoin="+str_nguoigui_nguoinhan+"||loaimahoa="+str_loaimahoa);
		      	webservice = new org.thesis.secutity.webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);////
		      	Log.i("tag","truoc khi goi ham request web service voi nguoigui_nguoin="+str_nguoigui_nguoinhan+"||loaimahoa="+str_loaimahoa);
		      	webservice.getkeyStringEncrypt();////
		      	Log.i(tag, "Da tao xong key va luu xuong sdcard/EncrypEmail/keymail");
 	 		}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-createkey", "err create key" +e.toString());
		}
 	 }
 	 
 	 public void mahoa()
 	 {
 		 try 
 		 {
 			if(str_loaimahoa.equalsIgnoreCase("AES"))
				{
					str_mess_encrypt = ENC_AES + encrypt_aes() + ENC_FOOT;
				}else if(str_loaimahoa.equalsIgnoreCase("DES"))
				{
					str_mess_encrypt = ENC_DES +encrypt_des() + ENC_FOOT;
				}else if(str_loaimahoa.equalsIgnoreCase(DESede) || str_loaimahoa.equalsIgnoreCase("3DES"))
				{
					str_mess_encrypt = ENC_TDES +encrypt_3des() + ENC_FOOT;
				}else if(str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY))
				{
					str_mess_encrypt = ENC_PUBLIC + encrypt_rsa_publickey() + ENC_FOOT;
				}
 			
// 			txt_encrypt.setText(str_mess_encrypt);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e( tag + "-mahoa: ", e.toString() );
		}
 	 }
 	 
 	public void dialog2()
    {
 		List<String>list_item = new ArrayList<String>();
 		list_item.add("AES");
 		list_item.add("DES");
 		list_item.add("3DES");
 		int iit = str_nguoinhan.split(";").length;
 		if(iit == 1) // neu chi co 1 ng nhan
 		{
 			list_item.add(PUBLIC_KEY);
 		}
//    	final CharSequence[] items  = {"AES", "DES", "3DES", PUBLIC_KEY };
 		final CharSequence[] items = list_item.toArray(new CharSequence[list_item.size()]);
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(getResources().getString(R.string.ChonLoaiMaHoa));
    	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) {
//    	        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    	        str_loaimahoa = items[item].toString();
    	        txt_loaimahoa.setText(str_loaimahoa);
    	    }
    	});
    	
    	builder.setPositiveButton("OK", new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
//				Toast.makeText(getApplicationContext(), "giai thuat : " + str_loaimahoa, Toast.LENGTH_SHORT).show();
				Log.v(tag, "giai thuat duoc chon : " + str_loaimahoa);
//				txt_loaimahoa.setText(str_loaimahoa);
				encrypt_action();
			}
		});
    	builder.setNegativeButton("Cancel", new OnClickListener() {
			
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				str_loaimahoa = "";
				Toast.makeText(getApplicationContext(), "huy ma hoa", Toast.LENGTH_SHORT).show();
				txt_loaimahoa.setText(str_loaimahoa);
			}
		});
    	
    	AlertDialog alert = builder.create();
    	alert.show();
    }
 	private class sync_encrypt extends AsyncTask<String, String, String>
 	{
 		ProgressDialog p = new ProgressDialog(encryptActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
 		@Override
 		protected String doInBackground(String... params) {
 			// TODO Auto-generated method stub
 			if(flag_getkey)
 			{
 				create_key();
 			}
 			else
 				mahoa();
 			return null;
 		}
 		@Override
 		protected void onPostExecute(String result) {
 			// TODO Auto-generated method stub
 			super.onPostExecute(result);
 			p.dismiss();
 			if(!flag_getkey)
 				txt_encrypt.setText(str_mess_encrypt);
 			
 			st.showmess(progress2);
 			if(flag_getkey)
 			{
 				continue_dialog();
 			}
 		}
 	}
 	public void continue_dialog()
 	{
 		try 
 		{
			AlertDialog.Builder builder = new Builder(this);
			builder.setMessage(getResources().getString(R.string.reg_suc_encrypt));
			builder.setPositiveButton(getResources().getString(R.string.Next), new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					mahoa();
					txt_encrypt.setText(str_mess_encrypt);
				}
			});
			builder.setNegativeButton(getResources().getString(R.string.Cancel), new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			
			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-continue dialog", e.toString());
		}
 	}
 	
 	public void sign_action_send()
 	{
 		try {
 			if(str_mess_plantext.length() == 0)
 			{
 				st.showmess(getResources().getString(R.string.err_encrypt_plantext));
 			}
 			else
 			{
 				str_mess_plantext = et_plantext.getText().toString().trim();
 				File savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC);
			 		if(!savedirsub.isDirectory())
			 		{
							savedirsub.mkdirs();
							Log.v(tag,"tao thu muc");
			 		}
 				String path_key_pri = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_nguoigui+" keypri.key";////
 				Log.v(tag, "path_key_pri = "+path_key_pri);////
 				str_pathkey = path_key_pri;
 				File f = new File(path_key_pri);
 				if(!f.isFile())
			      {
			    	 flag_getkey = true;
			      	 progress = getResources().getString(R.string.getkey);
			      	 progress2 = getResources().getString(R.string.getkey_suc);
			      }
			      else
			      {
			    	  flag_getkey = false;
			    	  progress = getResources().getString(R.string.sign_doing);
			    	  progress2 = getResources().getString(R.string.sign_ok);
			      }
 				new sync_sign().execute("sign");
 				
 			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + " sing action send", e.toString());
		}
 	}
 	
 	private class sync_sign extends AsyncTask<String, String, String>
 	{
 		ProgressDialog p = new ProgressDialog(encryptActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
 		@Override
 		protected String doInBackground(String... params) {
 			// TODO Auto-generated method stub
 			if(flag_getkey)
 			{
 				create_key_rsa_private();
 			}
 			else
 				sign2();
 			return null;
 		}
 		@Override
 		protected void onPostExecute(String result) {
 			// TODO Auto-generated method stub
 			super.onPostExecute(result);
 			p.dismiss();
 			if(!flag_getkey)
 				txt_sign.setText(SIGN + str_sign + "@sign");
 			
 			st.showmess(progress2);
 			if(flag_getkey)
 			{
 				sign_action_send();
 			}
 		}
 	}
 	
 	public void create_key_rsa_private()
 	{
 		try {
 			Log.v(tag, "file key chua ton tai , bat dau xin key");////
			webservice   = new  webserviceRequest(str_nguoigui_nguoinhan, "RSApi");
			webservice.requestMyRSAKey();
			Log.v(tag, "xin key thanh cong");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+" create key rsa private",e.toString());
		}
 	}
 	
 	public void sign2()
 	{
 		try {
 			Log.v(tag, "da co key tien hanh sign....");
//			rsa = new RSAControl(path_key_pri, path_key_pu);
			rsa = new RSAControl(str_pathkey, true);
			str_sign = rsa.sign(str_mess_plantext);
			Log.v(tag, "sign success:  " + str_sign);
 			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+" sign2", e.toString());
		}
 	}
 	
 	
 	
}
